package com.sadam.ui4;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.google.android.material.textfield.TextInputEditText;
import com.sadam.ui4.Data.MySqLiteOpenHelper;
import com.sadam.ui4.Data.User;

public class ActivityLogin extends AppCompatActivity {

    public static final String SHARED_PREFRENCES_CURRENT_USER = "SHARED_PREFRENCES_UI4_CURRENT_USER";

    private MySqLiteOpenHelper mySqLiteOpenHelper;
    private TextInputEditText usernameEditText, passwordEditText;
    private CheckBox agreementCheckBox;
    private Button loginButton;
    private TextView registerGuideText;
    private View loadingProgressBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);

        // 初始化数据库
        mySqLiteOpenHelper = new MySqLiteOpenHelper(this, MySqLiteOpenHelper.DATABASE_NAME, null, MySqLiteOpenHelper.DATABASE_VERSION);

        // 绑定控件
        usernameEditText = findViewById(R.id.usernameEditText);
        passwordEditText = findViewById(R.id.passwordEditText);
        agreementCheckBox = findViewById(R.id.agreementCheckBox);
        loginButton = findViewById(R.id.loginButton);
        registerGuideText = findViewById(R.id.registerGuideText);
        loadingProgressBar = findViewById(R.id.loadingProgressBar);

        // 登录按钮点击事件
        loginButton.setOnClickListener(v -> {
            if (!agreementCheckBox.isChecked()) {
                Toast.makeText(this, "请先同意服务协议", Toast.LENGTH_SHORT).show();
                return;
            }

            String username = usernameEditText.getText().toString().trim();
            String password = passwordEditText.getText().toString().trim();

            if (username.isEmpty()) {
                Toast.makeText(this, "用户名不能为空", Toast.LENGTH_LONG).show();
                return;
            }
            if (password.isEmpty()) {
                Toast.makeText(this, "密码不能为空", Toast.LENGTH_LONG).show();
                return;
            }

            // 显示加载动画
            setLoading(true);

            User user = User.login(mySqLiteOpenHelper, username, password);
            if (user != null) {
                // 登录成功
                Log.d("Login", "登录成功，头像路径: " + user.getAvatarPath());
                saveCurrentUserToSharedPreferences(this, user);
                Intent intent = new Intent(ActivityLogin.this, MainActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK); // 清除返回栈
                startActivity(intent);
            } else {
                Toast.makeText(this, "用户名或密码错误", Toast.LENGTH_SHORT).show();
            }

            setLoading(false);
        });

        // “前往注册”点击事件
        registerGuideText.setOnClickListener(v -> {
            Intent intent = new Intent(ActivityLogin.this, ActivityRegister.class);
            startActivity(intent);
        });
    }

    private void setLoading(boolean loading) {
        loadingProgressBar.setVisibility(loading ? View.VISIBLE : View.GONE);
        loginButton.setEnabled(!loading);
    }

    // 以下两个方法保持不变
    public static void saveCurrentUserToSharedPreferences(Context context, User current_user) {
        SharedPreferences.Editor editor = context.getSharedPreferences(SHARED_PREFRENCES_CURRENT_USER, MODE_PRIVATE).edit();
        editor.putLong("id", current_user.getId());
        editor.putString("name", current_user.getName());
        editor.putString("password", current_user.getPassword());
        editor.putString("selfIntroduction", current_user.getSelfIntroduction());
        editor.putString("avatarPath", current_user.getAvatarPath());
        editor.apply();
        Log.d("Login", "保存用户信息到SP - ID: " + current_user.getId() + ", 头像路径: " + current_user.getAvatarPath());
    }

    public static User getCurrentUserFromSharedPrefrences(Context context, MySqLiteOpenHelper helper) {
        SharedPreferences prefs = context.getSharedPreferences(SHARED_PREFRENCES_CURRENT_USER, MODE_PRIVATE);
        long id = prefs.getLong("id", 0);
        String name = prefs.getString("name", null);
        String password = prefs.getString("password", null);
        String intro = prefs.getString("selfIntroduction", "设置你的个人简介吧！");
        String avatarPath = prefs.getString("avatarPath", null);

        User user = new User(helper, id, name, password);
        user.setSelfIntroduction(intro);
        user.setAvatarPath(avatarPath);

        Log.d("Login", "从SP读取用户信息 - ID: " + id + ", 用户名: " + name + ", 头像路径: " + avatarPath);
        return user;
    }
}